#    Tichy
#
#    copyright 2008 Guillaume Chereau (charlie@openmoko.org)
#
#    This file is part of Tichy.
#
#    Tichy is free software: you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Tichy is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Tichy.  If not, see <http://www.gnu.org/licenses/>.



import logging
logger = logging.getLogger('App.I-O')

import os
import tichy
from tichy import gui
from tichy.gui import Vect
import sys
from tichy.style import Style        

class I_O_App(tichy.Application):
    name = 'Paroli-I/O'
    icon = 'icon.png'
    category = 'main' # So that we see the app in the launcher
    
    def run(self, parent=None, text = ""):
        if isinstance(text, str):
            text = tichy.Text(text)
        #print dir(parent.etk_obj)
        #parent.etk_obj.title_set('parent')
        #parent.etk_obj.hide_all()
        self.main = gui.main_edje()
        self.main.etk_obj.title_set('Paroli I/O')
        self.history_items = []
        self.edje_file = os.path.join(os.path.dirname(__file__),'paroli-i-o.edj')
        #dir(main.etk_obj)
        #print dir(main)
        #self.window = gui.Window(parent, modal=True)
        #self.window.etk_obj.theme_file_set('../tichy/gui_p/edje/paroli-in-tichy.edj')
        #print self.window.etk_obj.theme_file_get()
        #self.window.etk_obj.theme_group_set('tele')
        #print self.window.etk_obj.theme_group_get()
        #self.window.etk_obj.title_set('paroli dialer')
        #self.window.etk_obj.show_all()
        #print dir(self.window.etk_obj)
        #self.window.show()
        #self.window.etk_obj.propagate_color_set(0)
        #print self.window.etk_obj.children_get()
        gsm_service = tichy.Service('GSM')
        print dir(gsm_service.logs)
        print gsm_service.logs
        self.history = [('Ali', '099872394'),('bachus', '098953214'),('julius', '059321894'),('zacharias', '04326953214'),('zuberio', '09922153214'),('oliver', '03322153214'),('Paula', '0225623614')]
        
        
        self.history_scroller = ['one','two','three','four','five','six','seven','i']
        #,'i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i'
        self.edje_obj = gui.edje_gui(self.main,'i-o',self.edje_file)
        self.edje_obj.edj.layer_set(2)
        self.edje_obj.edj.show()
        
        self.edje_obj.edj.signal_callback_add("edit_btn_clicked", "*", self.edit_mode)
        self.edje_obj.edj.signal_callback_add("top-bar", "*", self.top_bar)
        
        history_box = gui.edje_box(self,'V',1)
        self.lists = gui.lists()
        try:
          #self.lists.generate_list(self,self.main.etk_obj.evas,self.history_scroller,history_edje,self.edje_obj,'history_item')
          self.history_objects_list = gui.contact_list(self.history,history_box,self.main.etk_obj.evas,self.edje_file,'history_item',self,kind='history')
        except Exception,e:
          print e
        to_2_swallowed = history_box.scrolled_view

        try:
          self.edje_obj.add(to_2_swallowed,history_box,"history-items")
        except Exception,e:
          print e
        history_box.box.show()
        
        #main.etk_obj.hide()
        #frame = self.view(self.edje_obj, back_button=True)
        #print str(main)
        #print "dir of evas ", dir(main.etk_obj.evas)
        #main.etk_obj.signal_callback_add("*", "*", self.self_test)
        #print main.etk_obj.callback_destroy_get()
        ###B4 mirko:
        #self.window = gui.Window(parent, modal = True)
        #frame = self.view(main, back_button=True)
        
        #vbox = gui.Box(frame, axis=1, expand=True)
        #self.text = text
        #self.text.view(vbox, editable = False)
        #k = Keyboard(vbox, expand=True)
        #k.connect('key-pressed', self.on_key)
        
        #hbox = gui.Box(vbox, axis = 0)
        
        #call_button = gui.Button(hbox)
        #call_button.connect('clicked', self.on_call)
        #gui.Label(call_button, "Call")
        
        #del_button = gui.Button(hbox)
        #gui.Label(del_button, "Del")
        #del_button.connect('clicked', self.on_del)
        
        #quit_item = frame.actor.new_action('Quit')
     
        yield tichy.Wait(self.main, 'back')
        print dir(self.main.children)
        for i in self.main.children:
          i.remove()
        self.main.etk_obj.hide()   # Don't forget to close the window
        
    
    def edit_mode(self, emission, source, param):
        #for i in self.history_objects_list.item_list:
            #print i[0]
        if emission.part_state_get(param)[0] == 'default' or emission.part_state_get(param)[0] == '':
            signal = 'edit'
            #emission.signal_emit('wait-mode',"*")
            
            emission.signal_emit('edit-mode',"*")
            
        else:
            #print "button pressed"
            emission.signal_emit('edit_button_to_wait',"")
            #print emission.part_state_get(edje_object)[0]
            signal = 'normal'
            
            for i in self.history_objects_list.item_list:
                    
              #if edje object state edit
              if i[1].part_state_get('edit-base')[0] == 'edit':
                    #destroy text in info field (missed etc)
                    #i[1].destroy()
                    
                    #remove all edje stuff from history item to be deleted
                    i[2].remove_all()
                    
              #TODO: add "real delete" on SIM  
                    
            emission.signal_emit('edit_button_to_default',"")

        for i in self.history_objects_list.item_list:
            i[1].signal_emit(signal,"")
        
        print "edit-mode emitted"
    
    def top_bar(self,emission, source, param):
        print "top bar pressed"
        print dir(self.main)
        self.main.emit('back')
        #emission.delete()
    
    def load_phone_book(self,orig,orig_parent,emission, source, param):
        print "load phone book called"
        print dir(orig)
        print orig.group
        try:
          new_edje = gui.edje_window(orig_parent,'tele-people',orig.gsm,orig.phone_book)
        except Exception,e:
          print e
        orig.extra_child = new_edje
        #try:
          #orig_parent.add(new_edje)
        #except Exception,e:
          #print e
        print "done"
        try:
          contacts_edje = gui.edje_box(self,'V',1)
        except Exception,e:
          print e  
         
        #try: 
          #self.contacts_obj = gui.edje_window(orig_parent,'people',self)
        #except Exception,e:
          #print e 
        #self.contacts_obj.layer_set(17)
        try: 
          self.lists = gui.lists()
        except Exception,e:
          print e 
          
        try: 
          print "self.lists.generate_contacts_list(self,orig_parent,self.phone_book,contacts_edje,self.edje_obj)"
          self.lists.generate_contacts_list(self,orig_parent.etk_obj.evas,self.phone_book,contacts_edje,self.edje_obj,'tele-contacts_item')
        except Exception,e:
          print e 
        
        try: 
          to_2_swallowed = contacts_edje.scrolled_view
        except Exception,e:
          print e 
        
        try: 
          print "new_edje.add(to_2_swallowed,contacts_edje)"
          new_edje.add(to_2_swallowed,contacts_edje)
        except Exception,e:
          print e 
        
        try: 
          contacts_edje.box.show()
        except Exception,e:
          print e 
    
    def on_key(self, w, k):
        self.text.value += k  # The view will automatically be updated
        
    def on_del(self, w):
        self.text.value = self.text.value[:-1]
        
    def calling(self,orig,orig_parent,emission, source, param):  
        print "calling"
        number = emission.part_text_get("num_field-label")
        #print number
        #yield Caller(self.edje_obj, number)
        
    def on_call(self, b):
        yield Caller(self.window, self.text.value)
       
    def self_test(self,emission, source, param):
        print "emission: ", str(emission)
        print "source: ", str(source)
        print "param: ", str(param)
        try:
            eval(source + '(self,self.parent,emission, source, param)')
        except Exception, e:
            dir(e)

    def wait_mode(self,instance,edje_object, emission, source,param):
        emission.signal_emit('wait-mode',"*")
        #print dir(emission.part_object_get('layover'))
        print emission.part_object_get('layover').render_op_get()
        print "wait-mode emitted"
        emission.part_object_get('layover').render_op()
    
    def edit_btn_clicked(self,instance,edje_object, emission, source,param):
        #print "edit_btn in paroli-i-o"
        #print len(self.history_items)
        try:
            print "state: ",emission.part_state_get("edit-button")[0]
        except Exception,e:
            print e
        if emission.part_state_get("edit-button")[0] == 'default' or emission.part_state_get("edit-button")[0] == '':
            #print "edit detected"
            signal = 'edit'
            #emission.signal_emit('wait-mode',"*")
                  
            #print "after for"
            
            try:
              emission.signal_emit('edit-mode',"*")
            except Exception,e:
                  print e  
            
        else:
            #print "button pressed"
            #emission.signal_emit('edit_button_to_wait',"*")
            #print emission.part_state_get(edje_object)[0]
            signal = 'normal'
            #print "normal detected"
            for i in self.history_items:
                    
              #if edje object state edit
              if i[0].part_state_get('edit-base')[0] == 'edit':
                    #destroy text in info field (missed etc)
                    i[1].destroy()
                    
                    #remove all edje stuff from history item to be deleted
                    i[2].remove_all()
                    
              #TODO: add "real delete" on SIM  
                    
            emission.signal_emit('edit_button_to_default',"*")

        
        #print "after if/else"
        for i in self.history_items:
            print "# :",str(i)
            try:
              i[0].signal_emit(signal,"")
            except Exception,e:
              print e
        
        print "edit-mode emitted"

# TODO: ??? make the Caller app better, using John idea : we define
#       for every call status the status of the gui.  Then we just
#       wait for status change and set up the gui in consequence It
#       means we have an automaton with a single state, much simpler
#       to deal with that what we have now
class Caller(tichy.Application):
    """This is the application that deal with the calling sequence
    """
    def run(self, parent, number):
        """number can be a string or an incoming call object"""
        # We open a new window for a call
        self.window = gui.Window(parent)
        frame = self.view(self.window, title = 'Dialer')
        vbox = gui.Box(frame, axis = 1)
        
        text = tichy.Text("Initialization")
        text.view(vbox)
        
        try:
            gsm_service = tichy.Service('GSM')
            # The case when we have an incoming call
            if isinstance(number, tichy.phone.Call):
                call = number
                
                text.value = "incoming %s" % call.number
                answer_button = gui.Button(vbox)
                gui.Label(answer_button, 'Answer')
                def on_answer(b):
                    b.destroy()
                    call.activate()
                answer_button.connect('clicked', on_answer)
            else:   # If not it means we want to initiate the call first
                call = gsm_service.create_call(number)
                call.initiate()
                text.value = "initiating %s" % number
            
            button = gui.Button(vbox)
            button_label = gui.Label(button, 'Cancel')
            i,args = yield tichy.WaitFirst(tichy.Wait(button, 'clicked'), tichy.Wait(call, 'activated'))
            if i == 1: # activated:
                # Now the call is active
                text.value = "calling %s" % call.number
                button_label.text = "hang up"
                i,args = yield tichy.WaitFirst(tichy.Wait(button, 'clicked'),
                                               tichy.Wait(call, 'released'))
            
            if call.status not in ['released', 'releasing']:
                text.value = "releasing %s" % call.number
                call.release()
                yield tichy.Wait(call, 'released')
            
        except Exception, e:
            import traceback
            logger.error("%s, %s", e, traceback.format_exc())
            yield tichy.Message(self.window, "Error", e.message)
            
        self.window.destroy()
        
        
class MyCallerService(tichy.Service):
    service = 'Caller'
    def call(self, parent, number):
        return Caller(parent, number)
        
